<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">

            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10rem;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="110"
                :model="formValue" style="width: 350rem" label-align="right">


                <NFormItem label="申请人部门:">
                  <NInput class="commonWidth" v-model:value="formValue.deptName" disabled placeholder="请输入申请人部门" />
                </NFormItem>
                <NFormItem label="申请人:">
                  <NInput class="commonWidth" v-model:value="formValue.userName" disabled placeholder="请输入申请人" />
                </NFormItem>

                <NFormItem label="开始时间:">
                  <NInput class="commonWidth" v-model:value="formValue.startDate" disabled placeholder="请选择开始时间">
                    <template #suffix>{{ formValue.startSessional }}</template>
                  </NInput>
                </NFormItem>
                <NFormItem label="结束时间:">
                  <NInput class="commonWidth" v-model:value="formValue.endDate" disabled placeholder="请选择结束时间">

                    <template #suffix>{{ formValue.endSessional }}</template>
                  </NInput>
                </NFormItem>

                <NFormItem label="请假类型:">
                  <NInput class="commonWidth" v-model:value="formValue.leaveTypeName" disabled placeholder="请选择请假类型" />
                </NFormItem>
                <NFormItem label="请假天数:">
                  <NInput class="commonWidth" v-model:value="formValue.leaveDay" disabled placeholder="请输入请假天数" />
                </NFormItem>

                <NFormItem label="请假原因:">
                  <NInput placeholder="请输入请假原因" style="width: 100%; min-height: 100rem" type="textarea"
                    v-model:value="formValue.leaveReason" disabled />
                </NFormItem>

                <NFormItem label="销假原因:" path="reportingLeaveReason">
                  <NInput placeholder="请输入销假原因" style="width: 100%; min-height: 120rem" type="textarea"
                    v-model:value="formValue.reportingLeaveReason" clearable :allow-input="noSideSpace" />
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>

  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">

          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" :loading="loading"
          v-if="formValue.entityId">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" :loading="loading" v-if="formValue.entityId">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NModal,
  useMessage,
  NSpin,
  NIcon,
  NImage,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { onMounted } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { LeaveModel } from '@/api/leave'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
  title: { type: String, default: () => '销假申请' },
  id: { type: [Number, String], default: () => null },
  flat: { default: () => false }
})
const message = useMessage()

const formValue = reactive<Record<string, any>>({
  startDate: null, //开始时间
  startSessional: null, //开始上下午
  endDate: null, //结束时间
  endSessional: null, //结束上下午
  userName: null, //申请人
  deptName: null, //申请人部门
  leaveDay: null, //请假天数
  leaveTypeName: null, //请假类型
  leaveReason: null, //请假原因
  reportingLeaveReason: null, //销假原因
  draftFlag: null, //草稿状态
  entityId: null, //流程实体id
  leaveApplyId: null //请假id
})
const rules = {
  reportingLeaveReason: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入销假原因')
      if (value?.length > 100) return new Error('销假原因字数不得超过100')
      return true
    }
  }
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 原因
const supplementaryReasonList: any = ref()
const getSupplementaryReasonList = async () => {
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'receiveOrDispatch',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A29'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  supplementaryReasonList.value = res.data
}
// 类型
const supplementaryTypeList: any = ref()
const getSupplementaryTypeList = async () => {
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'receiveOrDispatch',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A28'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  supplementaryTypeList.value = res.data
}
// 获取流程id
const hint = ref()
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: 'A0523'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  spinShow.value = false
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const confirm = (status: any) => {
  formRef.value?.validate(async (err) => {
    if (err) return (contentVisible.value = false)
    formValue.draftFlag = status
    contentContent.value = status ? '您确定要保存草稿吗？' : '您确定要提交申请吗？'
    contentVisible.value = true
  })
}
// 提交
const contentContent = ref()
const contentVisible = ref(false)
const submit = async () => {
  if ((props.id && props.flat) || (!props.id && !props.flat)) {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
      module: 'leave',
      api: 'shredLeaveAdd',
      override: {
        data: {
          reportingLeaveReason: formValue.reportingLeaveReason,
          entityId: formValue.entityId,
          leaveApplyId: formValue.leaveApplyId || props.id,
          draftFlag: formValue.draftFlag
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  } else {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
      module: 'leave',
      api: 'shredLeaveUpdate',
      override: {
        data: {
          reportingLeaveReason: formValue.reportingLeaveReason,
          entityId: formValue.entityId,
          leaveApplyId: formValue.leaveApplyId,
          draftFlag: formValue.draftFlag,
          id: props.id
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  }
  goSubmit()
}

//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draftFlag) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}

// 获取修改详情
const getShredLeaveInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'leave',
    api: 'leaveInfo',
    uri: {
      id: props.id
    }
  })
  if (error) return
  if (res.code !== 0) return
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    if (it == 'leaveDay') return (formValue[it] = res.data[it].toString())
    // @ts-ignore
    if (it == 'startDate' || it == 'endDate') return (formValue[it] = res.data[it].split(' ')[0])
    // @ts-ignore
    formValue[it] = res.data[it]
  })
}
// 获取修改详情
const getUpdateInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'leave',
    api: 'shredLeaveInfo',
    uri: {
      id: props.id
    }
  })
  if (error) return
  if (res.code !== 0) return
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    if (it == 'leaveDay') return (formValue[it] = res.data[it].toString())
    // @ts-ignore
    if (it == 'startDate' || it == 'endDate') return (formValue[it] = res.data[it].split(' ')[0])
    // @ts-ignore
    formValue[it] = res.data[it]
  })
}

watch(
  () => props.id,
  async () => {
    if (props.title == '销假编辑' && props.id) {
      await getUpdateInfo()
      getWorkFlow()
    }
    else if (props.title == '销假申请' && props.id) {
      await getShredLeaveInfo()
      getWorkFlow()
    }
  },
  { deep: true, immediate: true }
)
onMounted(async () => {
  getSupplementaryReasonList()
  getSupplementaryTypeList()
  getWorkFlow()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
